const express = require('express')
// 创建路由对象
const router = express.Router()

var mysql = require('mysql');
var pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'demo'//数据库名字
});

// 查询
router.get('/getList', (req, res) => {
  pool.getConnection(function (err, connection) {
    if (err) throw err; // not connected!
    // Use the connection
    // where name = ? 表示查询条件 查询name=?的数据
    connection.query('SELECT * FROM mons where name = ?', [req.query.name], function (error, results, fields) {
      // When done with the connection, release it.
      connection.release();
      console.log('结果', results);

      res.send({ "msg": '操作成功', 'code': 200, 'data': results })
      // res
      // Handle error after the release.
      if (error) throw error;

      // Don't use the connection here, it has been returned to the pool.
    });
  });
})

// 新增
router.post('/add', (req, res) => {
  pool.getConnection(function (err, connection) {
    if (err) throw err; // not connected!
    let params = [req.body.name, req.body.age, req.body.sex, req.body.adress]
    // Use the connection
    // where name = ? 表示查询条件 查询name=?的数据
    connection.query('INSERT INTO mons ( `name`, `age`, `sex`, `adress`) VALUES (?,?,?,?)', params, function (error, results, fields) {
      // When done with the connection, release it.
      connection.release();
      console.log('结果', results);

      res.send({ "msg": '操作成功', 'code': 200, 'data': results })
      // res
      // Handle error after the release.
      if (error) throw error;

      // Don't use the connection here, it has been returned to the pool.
    });
  });
})
// 将router暴露出去
module.exports = router
